/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa036is.utilities;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.sql.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DateEditor extends PropertyEditorSupport {

    public static final String DATE_FORMAT = "dd.MM.yyyy";

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null || text.isEmpty()) {
            setValue(null);
        } else {
            SimpleDateFormat sdc = new SimpleDateFormat(DateEditor.DATE_FORMAT);
            try {
                java.sql.Date date = new Date(sdc.parse(text).getTime());
                setValue(date);
            } catch (ParseException ex) {
                Logger.getLogger(DateEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public String getAsText() {
        Date date = (Date) getValue();
        if (date == null) {
            return null;
        } else {
            SimpleDateFormat sdc = new SimpleDateFormat(DateEditor.DATE_FORMAT);
            return sdc.format(date);
        }
    }
}
